package com.haixee.parkdemo.auth.jwt.alg;

import com.haixee.parkdemo.auth.enums.AuthScope;
import com.haixee.parkdemo.auth.jwt.JwsToken;
import com.haixee.parkdemo.auth.jwt.JwsTokenExtra;
import com.haixee.parkdemo.auth.jwt.JwtOperator;
import com.haixee.parkdemo.auth.properties.WebProperties;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;

/**
 * @author RUIFENG GUO
 * 2020/4/18 14:38
 */
@Slf4j
public class HMACJwt implements JwtOperator {

    private static final SignatureAlgorithm ALGORITHM = SignatureAlgorithm.HS512;

    private final long expire = 60 * 60 * 240;

    private final Key key;

    private String name;

    public HMACJwt() {
        key = Keys.secretKeyFor(ALGORITHM);
    }

    public HMACJwt(WebProperties.Jwt jwt) {
        key = Keys.hmacShaKeyFor(jwt.getKey().getBytes());
    }

    @Override
    public String generateJwt(Integer uid) {

        long expireTime = System.currentTimeMillis() + expire;

        return Jwts.builder()
                .signWith(key)
                .claim("uid", uid)
                .setExpiration(new Date(expireTime))
                .compact();
    }

    @Override
    public String generateJwtWithExtra(Integer uid, AuthScope scope, JwsTokenExtra extra) {
        long expireTime = System.currentTimeMillis() + expire;

        return Jwts.builder()
                .signWith(key)
                .claim("uid", uid)
                .claim("extra", extra)
                .claim("scope", scope.getCode())
                .setExpiration(new Date(expireTime))
                .compact();
    }

    @Override
    public JwsToken getToken(String token) {
        return getJwsToken(token, key);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public long getExpire() {
        return expire;
    }


}
